//
//  SY_PaymentWayViewController.m
//  ChatDemo-UI2.0
//
//  Created by Sylar on 2017/1/3.
//  Copyright © 2017年 Sylar. All rights reserved.
//

#import "SY_PaymentWayViewController.h"
#import <AlipaySDK/AlipaySDK.h>
#import "SY_PaymentResultViewController.h"
#import "SY_Payment_WebViewController.h"

@interface SY_PaymentWayViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    NSDictionary *_dict;
    
    NSString *typeId;
    NSInteger selectType;
}

@property (nonatomic, strong) UIScrollView *myScrollView;
@property (nonatomic, strong) UILabel *nameLabel;
@property (nonatomic, strong) UILabel *moneyLabel;
@property (nonatomic, strong) UILabel *studentNameLabel;
@property (nonatomic, strong) UIButton *payBtn;
@property (nonatomic, strong) UIImageView *img;
@property (nonatomic, strong) UITableView *payTypeTable;
@property (nonatomic, strong) NSMutableArray *payTypeArr;

@end

@implementation SY_PaymentWayViewController

- (void)loadView {
    
    [super loadView];
    
    self.navBar.nav_titleLabel.text = @"选择交费方式";
    
    [self.view setBackgroundColor:[UIColor whiteColor]];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self creatView];
    
    [self getPayWaysRequest];
    
    selectType = 0;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(paymentResult:) name:@"PaymentBySchool" object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

- (void)creatView {
    
    [self.view addSubview:self.myScrollView];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(15, 12, 100, 17)];
    label.text = @"基本信息";
    [label setFont:[UIFont systemFontOfSize:17]];
    [label setTextColor:colorFromHex(@"#3b3b3b")];
    [self.myScrollView addSubview:label];
    
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(15, 41, SCREENWIDTH, 0.5)];
    [lineView setBackgroundColor:colorFromHex(@"#DEDEDE")];
    [self.myScrollView addSubview:lineView];
    
    UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(15, lineView.bottom + 16, 80, 16)];
    label1.text = @"交费名称:";
    [label1 setFont:[UIFont systemFontOfSize:16]];
    [label1 setTextColor:colorFromHex(@"#979797")];
    [self.myScrollView addSubview:label1];
    
    self.nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(label1.right, label1.y, 200, 16)];
    self.nameLabel.text = self.detailModel.name;
    [self.nameLabel setFont:[UIFont systemFontOfSize:16]];
    [self.nameLabel setTextColor:colorFromHex(@"#3b3b3b")];
    [self.myScrollView addSubview:self.nameLabel];
    
    UILabel *label2 = [[UILabel alloc]initWithFrame:CGRectMake(15, label1.bottom + 15, 80, 16)];
    label2.text = @"交费金额:";
    [label2 setFont:[UIFont systemFontOfSize:16]];
    [label2 setTextColor:colorFromHex(@"#979797")];
    [self.myScrollView addSubview:label2];
    
    float money = self.detailModel.money/100.0;
    self.moneyLabel = [[UILabel alloc]initWithFrame:CGRectMake(label2.right, label2.y, 200, 16)];
    self.moneyLabel.text = [NSString stringWithFormat:@"%.2f元",money];
    [self.moneyLabel setFont:[UIFont systemFontOfSize:16]];
    [self.moneyLabel setTextColor:colorFromHex(@"#3b3b3b")];
    [self.myScrollView addSubview:self.moneyLabel];
    
    UILabel *label3 = [[UILabel alloc]initWithFrame:CGRectMake(15, label2.bottom + 15, 80, 16)];
    label3.text = @"交费对象:";
    [label3 setFont:[UIFont systemFontOfSize:16]];
    [label3 setTextColor:colorFromHex(@"#979797")];
    [self.myScrollView addSubview:label3];
    
    self.studentNameLabel = [[UILabel alloc]initWithFrame:CGRectMake(label3.right, label3.y, 200, 16)];
    self.studentNameLabel.text = self.detailModel.studentname;
    [self.studentNameLabel setFont:[UIFont systemFontOfSize:16]];
    [self.studentNameLabel setTextColor:colorFromHex(@"#3b3b3b")];
    [self.myScrollView addSubview:self.studentNameLabel];
    
    float contentHeight = [Utils resizeContentLabelHeightWithString:@"请您认真核对以上信息，如有错误请联系孩子所在班级班主任。" andLineSpacing:8 andFont:[UIFont systemFontOfSize:13] andMaxWidth:SCREENWIDTH - 30];
    
    UILabel *label4 = [[UILabel alloc]initWithFrame:CGRectMake(15, label3.bottom + 10, SCREENWIDTH - 30, contentHeight)];
    label4.text = @"请您认真核对以上信息，如有错误请联系孩子所在班级班主任。";
    label4.numberOfLines = 0;
    label4.lineBreakMode = NSLineBreakByCharWrapping;
    [label4 setFont:[UIFont systemFontOfSize:13]];
    [label4 setTextColor:colorFromHex(@"#3b3b3b")];
    [self.myScrollView addSubview:label4];
    
    UIView *lineView1 = [[UIView alloc]initWithFrame:CGRectMake(0, label4.bottom + 16, SCREENWIDTH, 10)];
    [lineView1 setBackgroundColor:colorFromHex(@"#F5F8FA")];
    [self.myScrollView addSubview:lineView1];
    
    UILabel *label5 = [[UILabel alloc]initWithFrame:CGRectMake(15, lineView1.bottom + 12, 150, 17)];
    label5.text = @"选择交费方式";
    [label5 setFont:[UIFont systemFontOfSize:17]];
    [label5 setTextColor:colorFromHex(@"#3b3b3b")];
    [self.myScrollView addSubview:label5];
    
    UIView *lineView2 = [[UIView alloc]initWithFrame:CGRectMake(15, lineView1.bottom + 41, SCREENWIDTH, 0.5)];
    [lineView2 setBackgroundColor:colorFromHex(@"#DEDEDE")];
    [self.myScrollView addSubview:lineView2];
    
    [self.myScrollView addSubview:self.payTypeTable];
    [self.payTypeTable setFrame:CGRectMake(0, lineView2.bottom + 12, SCREENWIDTH, 0)];
    
//    self.img = [[UIImageView alloc]initWithFrame:CGRectMake(40, lineView2.bottom + 25, 18, 18)];
//    [self.img setImage:[UIImage imageNamed:@"new_parents_noticehw_list_press_"]];
//    
//    [self.myScrollView addSubview:self.img];
    
    
    self.payBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.payBtn setFrame:CGRectMake(SCREENWIDTH/2.0 - 90, self.myScrollView.height - 110, 180, 40)];
    [self.payBtn setBackgroundColor:colorFromHex(@"#39adff")];
    [self.payBtn addTarget:self action:@selector(payAction) forControlEvents:(UIControlEventTouchUpInside)];
    [self.payBtn setTitleColor:colorFromHex(@"#ffffff") forState:(UIControlStateNormal)];
    [self.payBtn setTitle:@"确定交费" forState:(UIControlStateNormal)];
    self.payBtn.layer.cornerRadius = 20.0;
    [self.myScrollView addSubview:self.payBtn];
    
}


- (void)paymentResult:(NSNotification *)dict{
    
    NSLog(@"%@",dict);
    
    SY_PaymentResultViewController *resultVC = [[SY_PaymentResultViewController alloc]init];
    resultVC.resultDic = dict.userInfo;
    resultVC.payId = [NSString stringWithFormat:@"%ld",self.detailModel.payid];
    resultVC.payType = self->typeId;
    [self.navigationController pushViewController:resultVC animated:YES];
    
}

#pragma mark - Request

- (void)getPayWaysRequest {
    
    NSMutableDictionary *parmaDic = [[NSMutableDictionary alloc]init];
    
    [parmaDic setObject:@"api_receipt_paytype" forKey:@"method"];
    [parmaDic setObject:[NSString stringWithFormat:@"%ld",self.detailModel.receiptid] forKey:@"receiptid"];

    
    [Utils get:nil parameters:parmaDic success:^(NSInteger recode, id jsonObject) {
        
        NSArray *dataArr = [jsonObject objectForKey:@"re_data"];
        
        if (dataArr != nil && dataArr.count > 0) {
            
            self.payTypeArr = [[NSMutableArray alloc]init];
            
            for (NSDictionary *dic in dataArr) {
                
                [self.payTypeArr addObject:dic];
            }
            
            self->typeId = [NSString stringWithFormat:@"%@",[[self.payTypeArr firstObject] objectForKey:@"typeid"]];
            
            [self.payTypeTable setHeight:44*self.payTypeArr.count];
            [self.payTypeTable reloadData];
            
        }
        
    } failure:^(NSInteger recode, NSError *error) {
        
    }];
}

#pragma mark - Action

- (void)payAction {
    
    if ([typeId isEqualToString:@"1"]) {
        NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
        [dict setObject:@"api_receipt_pay" forKey:@"method"];
        [dict setObject:USERID forKey:@"userid"];
        [dict setObject:[NSString stringWithFormat:@"%ld",self.detailModel.payid] forKey:@"payid"];
        [dict setObject:typeId forKey:@"typeid"];
        
        [Utils noHUD_get:nil parameters:dict success:^(NSInteger recode, id jsonObject) {
            
            [self handleResultWithDic:jsonObject];
            
        } failure:^(NSInteger recode, NSError *error) {
            
        }];
    }else {
        
        SY_Payment_WebViewController *webVC = [[SY_Payment_WebViewController alloc]init];
        webVC.detailModel = self.detailModel;
        [self.navigationController pushViewController:webVC animated:YES];
        
    }
    
}

/**处理接口返回结果*/
- (void)handleResultWithDic:(NSDictionary *)dict{
    
    _dict = dict;
    
    int code = [[dict objectForKey:@"re_code"] intValue];
    NSString *re_info = [dict objectForKey:@"re_info"];
    
    if (code == 0) {
        
        [[AlipaySDK defaultService] payOrder:[[dict objectForKey:@"re_data"] objectForKey:@"paystr"] fromScheme:@"youer" callback:^(NSDictionary *resultDic) { //网页支付会走这个回调
            
            SY_PaymentResultViewController *resultVC = [[SY_PaymentResultViewController alloc]init];
            resultVC.resultDic = resultDic;
            resultVC.payId = [NSString stringWithFormat:@"%ld",self.detailModel.payid];
            resultVC.payType = self->typeId;
            [self.navigationController pushViewController:resultVC animated:YES];
            
        }];
        
    }else{ 
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self showHint:re_info];
        });
    }
}

#pragma mark - TableViewDataSource && TableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.payTypeArr count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellIdentifier"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"cellIdentifier"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    for (UIView *view in cell.contentView.subviews) {
        if (view.tag > 20) {
            [view removeFromSuperview];
        }
    }
    
    UIImageView *img = [[UIImageView alloc]initWithFrame:CGRectMake(40, 13, 18, 18)];
    img.tag = indexPath.row + 50;
    [cell.contentView addSubview:img];
    
    if (indexPath.row == selectType) {
        [img setImage:[UIImage imageNamed:@"new_parents_noticehw_list_press_"]];
    }else {
        [img setImage:[UIImage imageNamed:@"new_parents_noticehw_list_nor_"]];
    }
    
    UIImageView *defautImg = [[UIImageView alloc]initWithFrame:CGRectMake(img.right+33, 0, 0, 0)];
    
    NSString * picURL = [NSString stringWithFormat:@"http://file.e-shiyun.com%@",[[self.payTypeArr objectAtIndex:indexPath.row] objectForKey:@"typelogo"]];
    [defautImg sd_setImageWithURL:[NSURL URLWithString:picURL] placeholderImage:[UIImage imageNamed:@"em_empty_photo"]];
    
    [cell.contentView addSubview:defautImg];
    
    [defautImg sd_setImageWithURL:[NSURL URLWithString:picURL] placeholderImage:nil options:SDWebImageRetryFailed completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType,NSURL *imageUrl){
        CGSize size = image.size;
        CGFloat w = size.width;
        CGFloat H = size.height;
        
        [defautImg setWidth:w];
        [defautImg setHeight:H];
        [defautImg setY:22 - (H/2.0)];
    }];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    selectType = indexPath.row;
    typeId = [NSString stringWithFormat:@"%@",[[self.payTypeArr objectAtIndex:selectType] objectForKey:@"typeid"]];
    
    [self.payTypeTable reloadData];
}


#pragma mark - Get
- (UIScrollView *)myScrollView {
    
    if (_myScrollView == nil) {
        
        _myScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, SafeAreaTopHeight, SCREENWIDTH, SCREENHEIGH-SafeAreaTopHeight)];
        _myScrollView.backgroundColor = [UIColor whiteColor];
        _myScrollView.showsVerticalScrollIndicator = NO;
        _myScrollView.showsHorizontalScrollIndicator = NO;
        
    }
    
    return _myScrollView;
}

- (UITableView *)payTypeTable {
    
    if (_payTypeTable == nil) {
        _payTypeTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 0) style:(UITableViewStylePlain)];
        _payTypeTable.delegate = self;
        _payTypeTable.dataSource = self;
        _payTypeTable.rowHeight = 44;
        _payTypeTable.separatorStyle = UITableViewCellSeparatorStyleNone;
        _payTypeTable.scrollEnabled = NO;
        
    }
    return _payTypeTable;
}
@end
